package Map

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/attr"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	table_Map "sanguo/node/table/excel/table/Map"
	cs_message "sanguo/protocol/cs/message"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/enterMap"
	"sanguo/rpc/leaveMap"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionTeleportPoint struct {
	transaction.TransactionBase
	user     *user.User
	req      *codecs.Message
	resp     *cs_message.TeleportPointToC
	errcode  cs_message.EnumType
	role     *role.Role
	node_map cluster.PeerID
}

func (this *transactionTeleportPoint) GetModuleName() string {
	return "Map"
}

func (this *transactionTeleportPoint) GetReplyMsg() proto.Message {
	return &cs_message.TeleportPointToC{}
}

func (this *transactionTeleportPoint) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionTeleportPoint) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionTeleportPoint) EnterMap(node_map cluster.PeerID) {
	req := this.req.GetData().(*cs_message.TeleportPointToS)
	//读表
	reqMap := table_Map.Table_.IDMap[req.GetMapID()]
	if reqMap == nil {
		node_game.Infoln("no map scene")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	mapID := reqMap.ID
	pos := reqMap.DefaultPosition
	angle := reqMap.DefaultRotation

	storyStage, _ := this.role.GetRoleAttr().GetAttr(attr.StoryStage)

	arg := &ss_rpc.EnterMapReq{
		MapType:    proto.Int32(mapID),
		UserID:     proto.String(this.user.GetUserID()),
		Name:       proto.String(this.role.GetName()),
		ID:         proto.Uint64(this.role.GetID()),
		Lev:        proto.Int32(this.role.GetLev()),
		Portrait:   proto.Int32(this.role.GetPortrait()),
		Face:       proto.Int32(this.role.GetFace()),
		Hair:       proto.Int32(this.role.GetHair()),
		HairColor:  proto.Int32(this.role.GetHairColor()),
		EyeColor:   proto.Int32(this.role.GetEyeColor()),
		Cloth:      proto.Int32(this.role.GetCloth()),
		ClothColor: proto.Int32(this.role.GetClothColor()),
		Weapon1:    proto.Int32(this.role.GetWeapon1()),
		Weapon2:    proto.Int32(this.role.GetWeapon2()),
		Outline:    proto.Int32(this.role.GetOutline()),
		Game:       proto.String(node_game.GetSelfService().ToPeerID().ToString()),
		Pos: &ss_rpc.Position{
			X: proto.Int32(pos.X),
			Y: proto.Int32(pos.Y),
			Z: proto.Int32(pos.Z),
		},
		Angle:      proto.Int32(angle),
		StoryStage: proto.Int64(storyStage),
	}
	enterMap.AsynCall(node_map, arg, transaction.TransTimeoutMs, func(resp *ss_rpc.EnterMapResp, err error) {

		if !this.user.CheckTrans(this) {
			//trans已经结束
			return
		}
		if nil == err && resp.GetOk() == 1 {
			this.role.SetMapID(mapID)
			this.role.SetPos(pos.X, pos.Y, pos.Z)
			this.role.SetAngle(angle)

			this.node_map = node_map
			this.role.NodeMap = &this.node_map
			this.role.ChatChangeMap()

			node_game.Debugln("entermap", mapID, "ok")
			this.errcode = cs_message.EnumType_OK
			this.user.EndTrans(this)
		} else {
			node_game.Debugln("entermap", reqMap, "failed")
			this.errcode = cs_message.EnumType_ERROR
			this.user.EndTrans(this)
		}
	})
}

func (this *transactionTeleportPoint) Begin() {
	this.resp = &cs_message.TeleportPointToC{}
	node_map, err := cluster.Random("map")
	if nil != err {
		node_game.Debugln("no map server")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	this.role = roleModule.CurrentRole()
	if nil == this.role || !this.role.IsRoleModleData() {
		node_game.Debugln("no selected role")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
	} else {

		if this.role.NodeMap != nil {
			node_game.Debugln("leave old map", this.role.GetMapID())
			arg := &ss_rpc.LeaveMapReq{
				MapType: proto.Int32(this.role.GetMapID()),
				UserID:  proto.String(this.user.GetUserID()),
			}
			leaveMap.AsynCall(*this.role.NodeMap, arg, transaction.TransTimeoutMs, func(resp *ss_rpc.LeaveMapResp, err error) {
				if !this.user.CheckTrans(this) {
					//trans已经结束
					return
				}
				if nil == err && resp.GetOk() == 1 {
					this.role.NodeMap = nil
					this.EnterMap(node_map)
				} else {
					node_game.Debugln("leave old map", this.role.GetMapID(), "failed")
					this.errcode = cs_message.EnumType_ERROR
					this.user.EndTrans(this)
				}
			})
		} else {
			this.EnterMap(node_map)
		}
	}
}

func (this *transactionTeleportPoint) End() {
	if this.errcode == cs_message.EnumType_OK {
		this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_OK).Enum()

		req := this.req.GetData().(*cs_message.TeleportPointToS)
		//读表
		reqMap := table_Map.Table_.IDMap[req.GetMapID()]
		pos := reqMap.DefaultPosition
		this.resp.MapID = proto.Int32(req.GetMapID())
		this.resp.Position = &cs_message.Position{
			X: proto.Int32(pos.X),
			Y: proto.Int32(pos.Y),
			Z: proto.Int32(pos.Z),
		}
		this.resp.Angle = proto.Int32(reqMap.DefaultRotation)
	} else {
		this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_ERROR).Enum()
	}
	//node_game.Infoln("TeleportPoint:", this.resp)
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionTeleportPoint) Timeout() {
	this.errcode = cs_message.EnumType_RETRY
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.TeleportPointToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionTeleportPoint{
			user: user,
			req:  msg,
		}
	})
}
